package sample.util;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Callable;
import static sample.util.SSHUtils.getJSchSession;

/**
 * 多线程提供服务器连接
 *
 * @author wutc
 * @date 20210317
 *
 */

public class GetConnectionSession  implements Callable {
    private HashMap<String, String[]> serverMap = new HashMap<String, String[]>();
    private static Boolean flag ;
    private Iterator it ;
    private int mapsize ;
    private String[] keys;
    int keynum ;

    public GetConnectionSession(HashMap serverMap, int keynum){
        this.serverMap = serverMap;
        this.keynum = keynum;
        this.flag = true;
        this.mapsize = serverMap.size();
        this.it = serverMap.keySet().iterator();
        this.keys = new String[mapsize];
        for (int i = 0; i < mapsize; i++) {
            keys[i] = it.next().toString();
        }
    }

    @Override
    public Session call() throws Exception {
        Session session = null;
        while (flag){
            session = getConnectionSession();
        }
        return session;
    }
    //连接服务器 获取session
    private Session getConnectionSession() throws Exception {
        Session session = null;
        String key = getMapskey();

        String ip = key;
        String user = serverMap.get(key)[1];
        String pwd = serverMap.get(key)[2];
        int port = 22;// 端口号
        int timeout = 5*60*60*1000;

        if (Integer.parseInt(serverMap.get(key)[4])==1){
                //创建连接 并保存
            try {
                session = getJSchSession(ip, port, user, pwd, timeout);
                Thread.sleep(50);
            }catch (Exception e){
                //第一个异常输入换行
                System.out.println("\t"+ip+"获取连接异常"+e.getMessage());
            }

//            System.out.println(session.getHost());
        }
        return session;
    }

    public synchronized String getMapskey(){
        String key = keys[keynum];
        keynum++;
        if(keynum >= mapsize){
            flag = false;
        }
        // System.out.println("线程"+Thread.currentThread().getName()+"获取了key"+key+",此时的 keynum已经是:"+keynum );
        return key;
    }

}
